/**
 * 
 */

package com.chengyu.eyc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.chengyu.eyc.constant.EycConstants;
import com.chengyu.eyc.exception.GenericException;
import com.chengyu.eyc.utils.RedisUtil;

import cn.hutool.core.util.StrUtil;

/**
 * @author kevin
 *
 */
@Component
public class EycWechatRegisterHandlerInterceptor implements HandlerInterceptor {

    /**
     * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse, java.lang.Object)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String verifyCode = request.getParameter("verifyCode");
        if (StrUtil.isBlank(verifyCode)) {
            throw new GenericException("请填写验证码");
        }
        String phoneNumber = request.getParameter("phoneNumber");
        String key = EycConstants.CacheKey.getVerifyCdeKey(phoneNumber);
        if (!RedisUtil.exists(key)) {
            throw new GenericException("验证码已过期，请重新获取");
        }
        if (!StrUtil.equals(verifyCode, (String)RedisUtil.get(key))) {
            throw new GenericException("验证码不正确，请重新输入");
        }
        return Boolean.TRUE;
    }

}
